<?php

namespace module\index\controller;

use app\Controller;
use app\model\Order as Model;
use app\model\Activity;
use app\model\UserAddress;
use app\model\Coupon;
use app\model\City;

class Order extends Controller
{
    /**
     * 列表.
     * 
     */
    public function index()
    {
        $result = Model::withSearch(['mobile', 'activity_id'], input('get.'))->scope('user')->paginate([
            'list_rows'=> input('get.pageSize/d', 10),
        ]);
        return json([
            'items' => $result->items(),
            'total' => $result->total()
        ]);
    }
    /**
     * 保存.
     * 
     */
    public function save()
    {
        $model = new Model;
        $model->save($this->request->post());
        return json(['id' => $model->id, 'params' => $model->pay->payParams]);
    }

    /**
     * 详情.
     * 
     * @param int $id
     */
    public function read(int $id)
    {
        $model = Model::scope('user')->findOrFail($id);
        return json($model->toArray());
    }

    /**
     * 订单检查.
     *
     */
    public function checkout()
    {
        $params = $this->request->get();
        $model = Activity::findOrFail($params['activity_id']);
        // 根据地址计算配送费
        $address = UserAddress::scope('user')->where($params['address_id'] > 0 ? [['id', '=', $params['address_id']]] : [])->order('default', 'DESC')->find();
        $expressFee = 0;
        if($address){
            $prov_id = floor($address->dist_id / 10000);
            // 新疆、西藏:40元;甘肃、宁夏、青海、内蒙古、海南:20元
            $fees = ['54' => 40, '65' => 40, '62' => 20, '64' => 20, '63' => 20, '15' => 20, '46' => 20];
            $expressFee = $fees[$prov_id] ?? 0;
        }
        // 优惠券
        $coupon = Coupon::scope('mine')->where($params['coupon_id'] > 0 ? [['id', '=', $params['coupon_id']]] : [])->find();
        $couponFee = 0;
        if($coupon){
            $couponFee = $coupon->fee;
        }
        return json([
            'fee' => $model->fee + $expressFee - $couponFee,
            'couponFee' => $couponFee,
            'expressFee' => $expressFee,
            'activity' => $model->toArray(),
            'address' => $address->toArray(),
            'coupon' => $coupon
        ]);
    }
    /**
     * 更新.
     * 
     * @param int $id
     */
    public function update(int $id)
    {
        $model = Model::scope('user')->findOrFail($id);
        $model->save($this->request->post());
        return json($model->tpoArray());
    }
    /**
     * 删除.
     * 
     * @param int $id
     */
    public function del(int $id)
    {
        $model = Model::scope('user')->findOrFail($id);
        $model->delete();
        return json($model->toArray());
    }
    /**
     * 状态.
     * 
     * @param int $id
     */
    public function status(int $id)
    {
        $model = Model::findOrFail($id);
        $model->status = [1, 0][$model->status];
        $model->save();
        return json($model->tpoArray());
    }
}


